import type { FC } from 'react';
import { useMemo } from 'react';
import { Popover } from 'antd';
import ToolTabs from './tabs';
import Context from './context';
import classNames from 'classnames';
import ToolButton from '../ToolButton';
import Icon, { getSvgComponent } from '../Icon';
import { useSafeState, useMemoizedFn } from 'ahooks';
import type { MultiToolProps, ToolItem, ChildResult } from './types';
import styles from './styles.module.less';

type Icons = Record<string, ToolItem[]>;

const MultiTool: FC<MultiToolProps> = (props) => {
  const { selected, config } = props;
  const [open, setOpen] = useSafeState(false);
  const [icons, setIcons] = useSafeState<Icons>({});
  const [selectedChild, setSelectedChild] = useSafeState<ChildResult>();

  const tabs = useMemo(() => {
    return config.tabs || [];
  }, [config]);

  const defaultSvg = useMemo(() => {
    return getSvgComponent(config.icon);
  }, [config.icon]);

  const activeSvg = useMemo(() => {
    if (!selectedChild) {
      return null;
    }
    const { tab, selectedItem } = selectedChild;

    const activeTool = icons?.[tab]?.find(e => {
      return e.id === selectedItem.id
    });
    return activeTool?.svgComponent;
  }, [selectedChild, icons]);

  const svgComponent = useMemo(() => {
    return activeSvg || defaultSvg;
  }, [defaultSvg, activeSvg]);

  const onOpenChange = useMemoizedFn((open: boolean) => {
    if (tabs.length) setOpen(open);
  });

  const handleLoadedIcons = useMemoizedFn(
    (tab: string, items: ToolItem[]) => {
      icons[tab] = items;
      setIcons({ ...icons });
    }
  );

  const handleWrapperClick = useMemoizedFn(
    (selectedChild?: ChildResult) => {
      props.onClick?.({
        current: config,
        child: selectedChild
      });
    }
  );

  //子元素点击事件
  const handleToolClick = useMemoizedFn(
    (tab: string, item: ToolItem) => {
      const child = { tab, selectedItem: item };
      onOpenChange(false);
      setSelectedChild(child);
      handleWrapperClick(child);
    }
  );

  // 点击按钮
  const handleButtonClick = useMemoizedFn(() => {
    handleWrapperClick(selectedChild);
  });

  const renderHandle = () => {
    if (!tabs.length) {
      return null;
    }
    const className = classNames(
      styles.handle,

    );
    return (
      <Popover
        open={open}
        trigger={['click']}
        placement="right"
        destroyTooltipOnHide
        onOpenChange={onOpenChange}
        overlayClassName={styles.multi_tools}
        content={(
          <ToolTabs
            tabs={tabs}
            selectedChild={selectedChild}
          />
        )}
      >
        <div
          className={className}
          onClick={e => e.stopPropagation()}
        >
          <Icon icon="Handle" />
        </div>
      </Popover>
    );
  }

  return (
    <Context.Provider
      value={{
        onToolClick: handleToolClick,
        onLoadedIcons: handleLoadedIcons,
      }}
    >
      <div className={classNames(
        styles.wrapper,
        selected && styles.selected
      )}>
        <ToolButton
          selected={selected}
          tooltip={config.title}
          svgComponent={svgComponent}
          onClick={handleButtonClick}
          renderExtElem={renderHandle}
        />
      </div>
    </Context.Provider>
  );
}

export default MultiTool;